﻿using System;
using System.Collections.Generic;
using System.Text;
using Anonym.Models.Objects;
using Anonym.Models.Common;
using Anonym.Data.Entities;
using SqlSugar;
using System.Linq;
using Anonym.Common;

namespace Anonym.Service
{
    /// <summary>
    /// CMS端用户服务
    /// </summary>
    public class CmsService : BaseService
    {
        public CmsService(IServiceProvider p) : base(p) { }

        /// <summary>
        /// 获取账号管理列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<Cms_UserInfo> GetCmsUserData(Cms_UserInfo model)
        {
            int totalCount = 0; //总条数

            #region 单表查询分页

            //var table = Db.Queryable<Cms_User>();

            //if (!string.IsNullOrEmpty(model.Key))
            //    table = table.Where(w => w.RealName.Contains(model.Key) || w.EmployeeId.Contains(model.EmployeeId) || w.Phone.Contains(model.Phone));

            //if (model.State > -1)
            //    table = table.Where(w => w.State == model.State);

            //table = table.OrderBy(o => o.CreationTime, OrderByType.Desc);
            //List<Cms_User> data = table.ToPageList(model.PageIndex, model.PageSize, ref totalCount);

            #endregion

            #region 多表查询分页

            var list = Db.Queryable<Cms_User, Cms_User>((a, b) => new JoinQueryInfos(JoinType.Left, a.CreatorUserId == b.ID));

            if (!string.IsNullOrEmpty(model.Key))
                list = list.Where((a, b) => a.RealName.Contains(model.Key) || a.EmployeeId.Contains(model.EmployeeId) || a.Phone.Contains(model.Phone));

            if (model.State > -1)
                list = list.Where((a, b) => a.State == model.State);

            list = list.OrderBy((a, b) => a.CreationTime, OrderByType.Desc);

            List<Cms_UserInfo> data = list.Select<Cms_UserInfo>("a.*,b.RealName as CreateUserName").ToPageList(model.PageIndex, model.PageSize, ref totalCount);

            #endregion

            //处理用户组名称展示
            string userIds = "";
            data.ForEach(f =>
            {
                userIds += f.ID + ",";
            });
            if (userIds != "")
                userIds = userIds.TrimEnd(',');
            var groupMpList = Db.SqlQueryable<Cms_UserGroupMapInfo>("select a.*,b.name GroupName from Cms_UserGroupMap a left join Cms_usergroup b on a.groupid= b.id where a.userid in (" + userIds + ")").ToList();

            data.ForEach(f =>
            {
                f.GroupName = GetGroupName(f.ID, groupMpList);
            });

            return data;
        }
        private string GetGroupName(long id, List<Cms_UserGroupMapInfo> list)
        {
            string ret = "";
            list.ForEach(f =>
            {
                if (f.UserId == id)
                    ret += f.GroupName + ",";
            });
            if (ret != "")
                ret = ret.TrimEnd(',');
            return ret;
        }

        /// <summary>
        /// 员工编辑
        /// </summary>
        /// <returns></returns>
        public ReturnValue EditCmsUser(Dictionary<string, string> dic)
        {
            long id = dic.GetDicByLong("id");
            Cms_User model = new Cms_User();

            if (id > 0) //修改
            {
                model = Db.Queryable<Cms_User>().InSingle(id);
                if (model == null)
                {
                    Result.Msg = "未查询到员工";
                    return Result;
                }
                model.DictionaryFill(dic, "id");

                #region 验证
                Result.Msg = model.VerifyEmpty("phone 电话号码,RealName 员工姓名");
                if (Result.Msg != "")
                    return Result;

                if (!model.Phone.VerifyPhone())
                {
                    Result.Msg = "手机号格式不正确";
                    return Result;
                }

                if (Db.Queryable<Cms_User>().Where(w => w.Phone == model.Phone && w.ID != model.ID).Count() > 0)
                {
                    Result.Msg = "该手机号已被注册过";
                    return Result;
                }

                if (model.State != 1 && model.State != 0)
                {
                    Result.Msg = "请选员工状态，或员工状态有误";
                    return Result;
                }

                #endregion

                if (Db.Updateable(model).ExecuteCommand() <= 0)
                {
                    Result.Msg = "修改失败";
                    return Result;
                }
            }
            else  //新增
            {
                model.DictionaryFill(dic);

                #region 验证
                Result.Msg = model.VerifyEmpty("name 登录账号,phone 电话号码,RealName 员工姓名,Password 登录密码");
                if (Result.Msg != "")
                    return Result;

                if (!model.Phone.VerifyPhone())
                {
                    Result.Msg = "手机号格式不正确";
                    return Result;
                }

                if (Db.Queryable<Cms_User>().Where(w => w.Phone == model.Phone).Count() > 0)
                {
                    Result.Msg = "该手机号已被注册过";
                    return Result;
                }

                if (Db.Queryable<Cms_User>().Where(w => w.Name == model.Name).Count() > 0)
                {
                    Result.Msg = "该登录账号已被注册过";
                    return Result;
                }

                if (model.Password.Length < 6)
                //if (password.Length != 32)
                {
                    Result.Msg = "密码长度不能小于6位";
                    return Result;
                }
                #endregion

                model.CreationTime = DateTime.Now;
                model.Password = model.Password.ToMd532();
                model.EmployeeId = CreateEmployeeId();

                if (Db.Insertable(model).ExecuteCommand() <= 0)
                {
                    Result.Msg = "新增失败";
                    return Result;
                }
            }

            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 创建员工id
        /// </summary>
        /// <returns></returns>
        private string CreateEmployeeId()
        {
            string str = "HDL000000000000000";
            long maxId = Db.Queryable<Cms_User>().Max(m => m.ID) + 1;
            return str.Substring(0, 9 - maxId.ToString().Length) + maxId;
        }

        /// <summary>
        /// 账号关联角色
        /// </summary>
        /// <returns></returns>
        public ReturnValue EditUserGroupMap(Dictionary<string, string> dic)
        {
            long UserId = dic.GetDicByLong("UserId");
            string GroupIds = dic.GetDicByString("GroupIds");

            List<string> GroupIdsList = new List<string>();
            if (GroupIds != "")
                GroupIdsList = dic.GetDicByString("GroupIds").Split(',').ToList();

            bool HaveDuplicates = GroupIdsList.GroupBy(i => i).Where(g => g.Count() > 1).Count() >= 1;
            if (HaveDuplicates)
            {
                Result.Msg = "有重复id，请检查";
                return Result;
            }

            List<Cms_UserGroupMap> userGroupMapList = new List<Cms_UserGroupMap>();

            GroupIdsList.ForEach(f =>
            {
                Cms_UserGroupMap o = new Cms_UserGroupMap();
                o.UserId = UserId;
                o.GroupId = int.Parse(f);
                userGroupMapList.Add(o);
            });

            try
            {
                //带事务操作
                Db.Ado.BeginTran();

                var ret = Db.Deleteable<Cms_UserGroupMap>().Where(w => w.UserId == UserId).ExecuteCommand();
                if (ret < 0)
                {
                    Result.Msg = "添加信息失败";
                    Db.Ado.RollbackTran();
                    return Result;
                }

                if (GroupIdsList != null && GroupIdsList.Count > 0)
                {
                    if (Db.Insertable(userGroupMapList).ExecuteCommand() < 1)
                    {
                        Result.Msg = "添加信息失败";
                        Db.Ado.RollbackTran();
                        return Result;
                    }
                }

                Db.Ado.CommitTran();
                Result.Success = true;
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
                Result.Msg = ex.Message;
            }

            return Result;
        }

        /// <summary>
        /// 获取员工详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValue GetCmsUserDetail(long id)
        {
            Cms_User model = Db.Queryable<Cms_User>().InSingle(id);
            if (model == null)
            {
                Result.Msg = "未查询到数据";
                return Result;
            }
            Cms_Company company = Db.Queryable<Cms_Company>().InSingle(model.CompanyId);
            if (company == null)
            {
                Result.Msg = "未查询到数据";
                return Result;
            }

            Result.Data = new
            {
                model.ID,
                model.EmployeeId,
                CompanyName = company.Name,
                model.RealName,
                model.Name,
                model.Phone,
                model.State,
                StateList = Tools.EnumModelToSelectItem(typeof(EnumModel.CmsUserState)),
            };
            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <returns></returns>
        public ReturnValue GetUserGroupData(Dictionary<string, string> dic)
        {
            string key = dic.GetDicByString("key");
            long userId = dic.GetDicByLong("userid");

            string sql = @"
select a.*,b.id, (CASE WHEN b.id IS NULL THEN 0 ELSE 1 END) IsAuthority from cms_usergroup a 
	left join (select * from Cms_UserGroupMap where userid=@userid) b on a.id = b.groupid
	where a.name like @key
";

            List<Cms_UserGroupInfo> list = Db.Ado.SqlQuery<Cms_UserGroupInfo>(sql, new { userid = userId, key = "%" + key + "%" });

            Result.Data = list.Select(s => new
            {
                s.Name,
                s.IsAuthority,
            });
            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 角色管理列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValue CmsUserGroupIndexData(Dictionary<string, string> dic)
        {
            Cms_UserGroupInfo model = new Cms_UserGroupInfo();
            model.DictionaryFill(dic);
            long id = 0;
            long.TryParse(dic["key"], out id);

            int totalCount = 0; //总条数

            var list = Db.SqlQueryable<Cms_UserGroupInfo>("select a.*,b.name CreatorUserName from Cms_UserGroup a left join cms_user b on a.CreatorUserId = b.id");

            if (!string.IsNullOrEmpty(model.Key))
                list = list.Where(w => w.Name.Contains(model.Key) || w.ID == id);

            if (model.State > -1)
                list = list.Where(w => w.State == model.State);

            list = list.OrderBy(o => o.CreationTime, OrderByType.Desc);

            List<Cms_UserGroupInfo> data = list.ToPageList(model.PageIndex, model.PageSize, ref totalCount);

            Result.Data = data.Select(s => new
            {
                s.ID,
                s.Name,
                s.State,
                StateName = ((EnumModel.CmsUserGroupState)s.State).ToString(),
                s.CreatorUserName,
                CreationTime = s.CreationTime.ToDateString(),
            });
            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <returns></returns>
        public ReturnValue EditCmsUserGroup(Dictionary<string, string> dic)
        {
            long id = dic.GetDicByLong("id");
            string name = dic.GetDicByString("name");
            Cms_UserGroup model = new Cms_UserGroup();

            Result.Msg = model.VerifyEmpty("name 角色名称");
            if (Result.Msg != "")
                return Result;

            if (id > 0) //修改
            {
                model = Db.Queryable<Cms_UserGroup>().InSingle(id);
                if (model == null)
                {
                    Result.Msg = "未查询到数据";
                    return Result;
                }
                model.DictionaryFill(dic, "id");

                if (Db.Updateable(model).ExecuteCommand() <= 0)
                {
                    Result.Msg = "修改失败";
                    return Result;
                }
            }
            else  //新增
            {
                model.DictionaryFill(dic);

                model.CreationTime = DateTime.Now;

                if (Db.Insertable(model).ExecuteCommand() <= 0)
                {
                    Result.Msg = "新增失败";
                    return Result;
                }
            }

            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 角色授权页面数据
        /// </summary>
        /// <returns></returns>
        public ReturnValue CmsUserGroupAccreditData(long id)
        {
            string sql = @"
select a.*,b.id, (CASE WHEN b.id IS NULL THEN 0 ELSE 1 END) IsAuthority from cms_menu a 
	left join (select * from Cms_MenuPermissions where groupid=@id) b on a.id = b.MenuId
";

            List<Cms_MenuInfo> list = Db.Ado.SqlQuery<Cms_MenuInfo>(sql, new { id = id });

            Result.Data = list.Select(s => new
            {
                s.Name,
                s.IsAuthority,
            });
            Result.Success = true;
            return Result;
        }

        /// <summary>
        /// 角色授权数据编辑
        /// </summary>
        /// <returns></returns>
        public ReturnValue EditCmsUserGroupAccredit(Dictionary<string, string> dic)
        {
            long groupId = dic.GetDicByLong("groupId");
            string menuIds = dic.GetDicByString("menuIds");

            List<string> menuIdsList = new List<string>();
            if (menuIds != "")
                menuIdsList = dic.GetDicByString("menuIds").Split(',').ToList();

            bool HaveDuplicates = menuIdsList.GroupBy(i => i).Where(g => g.Count() > 1).Count() >= 1;
            if (HaveDuplicates)
            {
                Result.Msg = "有重复id，请检查";
                return Result;
            }

            List<Cms_MenuPermissions> mapList = new List<Cms_MenuPermissions>();

            menuIdsList.ForEach(f =>
            {
                Cms_MenuPermissions o = new Cms_MenuPermissions();
                o.MenuId = int.Parse(f);
                o.GroupId = groupId;
                mapList.Add(o);
            });

            try
            {
                //带事务操作
                Db.Ado.BeginTran();

                var ret = Db.Deleteable<Cms_MenuPermissions>().Where(w => w.GroupId == groupId).ExecuteCommand();
                if (ret < 0)
                {
                    Result.Msg = "添加信息失败";
                    Db.Ado.RollbackTran();
                    return Result;
                }

                if (menuIdsList != null && menuIdsList.Count > 0)
                {
                    if (Db.Insertable(mapList).ExecuteCommand() < 1)
                    {
                        Result.Msg = "添加信息失败";
                        Db.Ado.RollbackTran();
                        return Result;
                    }
                }

                Db.Ado.CommitTran();
                Result.Success = true;
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
                Result.Msg = ex.Message;
            }

            return Result;
        }
    }
}
